import {
  clearLocalStorageByKey,
  loadObjFromLocalStorage,
  saveObjToLocalStorage,
} from '@/utils/StorageUtil'

export function checkRouteDefine(routes, routeNameArr = []) {
  routes.forEach(route => {
    if (route.component) {
      if (!route.name) {
        throw new Error('路由定义中存在定义了component属性，但未定义name的路由')
      }
      if (typeof route.name === 'symbol') {
        throw new Error('路由name值只能是字符类型，不能是symbol类型')
      }
      if (routeNameArr.includes(route.name)) {
        throw new Error(`路由name值[${route.name}]重复`)
      }
      routeNameArr.push(route.name)
    }
    if (route.children && route.children.length > 0) {
      checkRouteDefine(route.children, routeNameArr)
    }
  })
}

export function convertTabMetadataArr(arr, map, fieldMapping) {
  return arr.reduce((prev, cur) => {
    const item = convertTabMetadata(cur, fieldMapping)
    map.set(item.index, item)
    prev.push(item)
    if (item.children && item.children.length > 0) {
      convertTabMetadataArr(item.children, map, fieldMapping)
    }
    return prev
  }, [])
}

export function convertTabMetadata(tabData, fieldMapping) {
  const index = tabData[fieldMapping.index]
    ? tabData[fieldMapping.index]
    : undefined
  const name = tabData[fieldMapping.name]
    ? tabData[fieldMapping.name]
    : undefined
  const icon = tabData[fieldMapping.icon]
    ? tabData[fieldMapping.icon]
    : undefined
  const routePath = tabData[fieldMapping.routePath]
    ? tabData[fieldMapping.routePath]
    : undefined
  const children = tabData[fieldMapping.children]
    ? tabData[fieldMapping.children]
    : undefined
  const customDataMap = tabData[fieldMapping.customDataMap]
    ? tabData[fieldMapping.customDataMap]
    : undefined
  const closeAble = tabData[fieldMapping.closeAble] === false ? false : true
  const keepAlive = tabData[fieldMapping.keepAlive] === false ? false : true

  return {
    index,
    name,
    icon,
    routePath,
    children,
    customDataMap,
    closeAble,
    keepAlive,
  }
}

const openedTabDataLocalStorageKey = '_tabData'

export function saveOpenedTabDataToLocalStorage(arr) {
  saveObjToLocalStorage(openedTabDataLocalStorageKey, arr)
}

export function loadOpenedTabDataFromLocalStorage() {
  const ret = loadObjFromLocalStorage(openedTabDataLocalStorageKey)
  return ret ? ret : []
}

export function clearOpenedTabDataFromLocalStorage() {
  clearLocalStorageByKey(openedTabDataLocalStorageKey)
}
